import { Component, Input } from '@angular/core';
import { FolderDetailsDto } from '../../dto/folderDetailsDto';
import { MatTableModule } from '@angular/material/table';
import { CoreService } from '../../service/core.service';
import { common, file, fileInfoBaseDto, folder, QueryDto } from 'ispace.core.main';
import { CdkMenuModule } from '@angular/cdk/menu';
import { CommonModule } from '@angular/common';
import {ClipboardModule} from '@angular/cdk/clipboard';
import { PropertiesCmpComponent } from '../properties-cmp/properties-cmp.component';
import { MatDialog } from '@angular/material/dialog';
import {Clipboard} from '@angular/cdk/clipboard';
import { DriverOperationDto } from 'ispace_doa';
import { RenameCmpComponent } from '../rename-cmp/rename-cmp.component';

const ELEMENT_DATA: fileInfoBaseDto[] = [
];

@Component({
  selector: 'app-content-cmp',
  standalone: true,
  imports: [MatTableModule,CdkMenuModule,CommonModule,ClipboardModule],
  templateUrl: './content-cmp.component.html',
  styleUrl: './content-cmp.component.scss'
})
export class ContentCmpComponent {
 

itemSelected(item: fileInfoBaseDto) {
 return this.coreSvc.selectedItemList.value.some(s => s.id == item.id);  
}
 

clickItem(event: MouseEvent,item: fileInfoBaseDto) {  
 
  if(event.button != 0){
    return;
  }

  const isCtrlPressed = event.ctrlKey || event.metaKey; // 检查是否按下了 Ctrl 键

  if (isCtrlPressed) { 
    if(!this.coreSvc.selectedItemList.value.includes(item)) {
    this.coreSvc.selectedItemList.value.push(item);
    return;
    }
  }

  const isShiftPressed = event.shiftKey; // 检查是否按下了 Shift 键
  if (isShiftPressed) {

    if(this.coreSvc.selectedItemList.value.length == 0) {
      this.coreSvc.selectedItemList.value.push(item);
      return;
    }
    const firstIndex = this.dataSource.indexOf(this.coreSvc.selectedItemList.value[0]);
    const lastIndex = this.dataSource.indexOf(item);
    const start = Math.min(firstIndex, lastIndex);
    const end = Math.max(firstIndex, lastIndex);
    this.coreSvc.selectedItemList.next(this.dataSource.slice(start, end + 1)); 
    return;
    }

  
  this.coreSvc.selectedItemList.next([item]); 
}

isMutiSelectMenue(data: fileInfoBaseDto) { 
    if(this.coreSvc.selectedItemList.value.length>1)
    {
      if(this.coreSvc.selectedItemList.value.some(s=>s.id==data.id)) {
        return true;
      }
    }
    return false;
  }



multi_copy() {
  let strList:string[] = [];
  this.coreSvc.selectedItemList.value.forEach(s=>{
    strList.push("$ispace copy fileBase "+ s.path +" "+ (s.isDir?"folder":"file"));
  })

  let str = strList.join("\n").replace('\r\n', '\n');
  this.clipboard.copy(str);
}
multi_shear() { 
  let strList:string[] = [];
  this.coreSvc.selectedItemList.value.forEach(s=>{
    strList.push("$ispace shear fileBase "+ s.path +" "+ (s.isDir?"folder":"file"));
  })
  let str = strList.join("\n").replace('\r\n', '\n');

  this.clipboard.copy(str);
}

multi_remove() {
  this.removeItem(this.coreSvc.selectedItemList.value); 
}

 removeItem(data: fileInfoBaseDto|fileInfoBaseDto[]) { 
  if(Array.isArray(data)) {
    data.forEach(s => {
      this.removeItem(s);
    })
    return;
  }
  if(data.isDir) {
    folder.remove(this.coreSvc.path.value.path, data.name!).subscribe(s => {
      this.coreSvc.refresh();
    }, e => {
      console.error(e);
    })
  }
  else {
    file.remove(this.coreSvc.path.value.path, data.name!).subscribe(s => {
      this.coreSvc.refresh();
    }, e => {
      console.error(e);
    })
  }
} 




formatFileSize(size: number|undefined) {
  if (size === undefined) {
    return "N/A";
  }
  const units = ["B", "KB", "MB", "GB", "TB"];
  let unitIndex = 0;
  while (size >= 1024 && unitIndex < units.length - 1) {
    size /= 1024;
    unitIndex++;
  }
  return `${size.toFixed(2)} ${units[unitIndex]}`;
}
async open(data: fileInfoBaseDto) {
  if(data.isDir) {
    let path = this.coreSvc.path.value.path + "/" + data.name;
    path = path.replace("//", "/");

    this.coreSvc.open(path);
    
    return;
  }
  if(data.isSymbolicLink) {
    let path ='/'+ data.symbolicLinkPath!; 
    this.coreSvc.open(path);
    return;
  }
 
  await this.init_ext_operations(data);
  const op =  this.ext_operations.find(s=>s.name =="打开");
  if(op && op.id>0){
    this.ext_operation_execute(op,data);
  }
  else{ 
   this.coreSvc.setMsg("打开不支持");
  }

}

isOpen(data:fileInfoBaseDto)
{
  if(data.isDir){
    return true;
  }
  if(data.isSymbolicLink) { 
    return true;
  }
  const op = this.ext_operations.find(s=>s.name =="打开");
  return (op && op.id>0);
}

copy(data:fileInfoBaseDto) {
 
  this.clipboard.copy("$ispace copy fileBase "+this.coreSvc.path.value.path + "/" + data.name+" "+(data.isDir?"folder":"file"));
}
shear(data:fileInfoBaseDto) {
  this.clipboard.copy("$ispace shear fileBase "+this.coreSvc.path.value.path + "/" + data.name+" "+(data.isDir?"folder":"file"));
}
rename(data:fileInfoBaseDto) {
 const d = this.dialog.open(RenameCmpComponent, {
    data: data,
  });
  d.afterClosed().subscribe(result => {
      if (result) { 
      }
    });
}
remove(data:fileInfoBaseDto) {  
  if(data.isDir) {
    folder.remove(this.coreSvc.path.value.path, data.name!).subscribe(s => {
      this.dataSource = this.dataSource.filter(s => s.id != data.id);
    }, e => {
      this.coreSvc.setMsg(e.message);
    })
  }
  else {
    file.remove(this.coreSvc.path.value.path, data.name!).subscribe(s => {
      this.dataSource  = this.dataSource.filter(s => s.id != data.id);
    }, e => {
      this.coreSvc.setMsg(e.message);
    })
  }
}
properties(data:fileInfoBaseDto) {
  if(this.isDesktop()) { 
    const op = this.ext_operations.find(s=>s.name =="属性");
    if(op && op.id>0){
      this.ext_operation_execute(op,data);
      return;
    }
  }
  this.dialog.open(PropertiesCmpComponent, {
    data: {
      path: this.coreSvc.path.value.path + "/" + data.name,
      type: data.isDir ? "folder" : "file",
    },
  }); 
}
  // id name size mode modTime isDir sys 
  displayedColumns: string[] = ['name', 'modTime', 'type',  'size'];
  dataSource = ELEMENT_DATA;
 
  address = ""
  query = ""

  constructor(public coreSvc:CoreService,private clipboard:Clipboard,public dialog: MatDialog) {
     
    coreSvc.path.subscribe(s => {
      if(s.path == this.address) {
        return;
      }

      this.address = s.path;

      this.load(s.path,this.query);
    });

    coreSvc.query.subscribe(s => {
      if(s == this.query) {
        return;
      }

      this.query = s;

      this.load(this.address,s);
    });

    coreSvc.refreshSub.subscribe(s => {
      this.load(this.address,this.query);
    });

  }

  load(path: string, name: string) {
     
    let query = new QueryDto(); 
    query.name = name;
    query.path = path;
    folder.children(query).subscribe({
      next: (s) => { 
        s.forEach(s => {
          s.type = s.isDir ? "folder" : "file";
          s.iconUrl = s.isDir ? "images/folder.png" : "images/unknow.png"
           
        }) 

        this.dataSource = s;
        this.coreSvc.currentFiles.next(s);
        this.coreSvc.setMsg(`已加载 ${s.length} 个文件`);
      }, error: (e: any) => {
        console.error(e);
      }
    })
  
  }
  

  isDesktop() {
    return this.coreSvc.env.value == 'desktop' && this.coreSvc.desktopOpenApi.value;
  }

  ext_operations: DriverOperationDto[] = [];
  ext_operations_current: DriverOperationDto[] = [];

  async init_ext_operations(data:fileInfoBaseDto) {  
    if(this.coreSvc.env.value == 'desktop' && this.coreSvc.desktopOpenApi.value){
      this.ext_operations = await this.coreSvc.desktopOpenApi.value!.getOperations(this.address+"/"+data.name!,data.isDir!);  
      if(data.isDir){
        this.ext_operations_current = this.ext_operations.filter(s => s.name !=="打开"&&s.name !=="复制"&&s.name !=="剪切"&&s.name !=="重命名"&&s.name !=="删除"&&s.name !=="属性");
        return;
      }
      this.ext_operations_current = this.ext_operations.filter(s => s.name !=="打开"&&s.name !=="资源管理器打开" &&s.name !=="复制"&&s.name !=="剪切"&&s.name !=="重命名"&&s.name !=="删除"&&s.name !=="属性");
     
   
    }
  }
  
  async ext_operation_execute(operation: DriverOperationDto,data:fileInfoBaseDto) {
    if(this.coreSvc.env.value == 'desktop' && this.coreSvc.desktopOpenApi.value){   
            if(data.isDir) {
        let driver = await this.coreSvc.desktopOpenApi.value.GetDriverList(1); 
        if(driver && driver.length==1){
            data.iconUrl = driver[0].fileIconUrl;
        }
      }
      else {
        let ops = this.ext_operations.find(s=> s.name == "打开",0);
        if(ops && ops.id>0){
          let driver = await this.coreSvc.desktopOpenApi.value.GetDriverList(ops.driverId);
          if(driver && driver.length>0){
            data.iconUrl = driver[0].fileIconUrl;
          }
        } 
      }

      await this.coreSvc.desktopOpenApi.value!.execute(operation.driverId, operation.id,this.address+"/"+data.name!, data.isDir! ? "folder" : "file",data);
    }
    else {
      this.coreSvc.setMsg("当前环境不支持扩展操作");
    }
  }

  async itemMeneOpen(data:fileInfoBaseDto){
    if(this.coreSvc.selectedItemList.value.length>1 && this.coreSvc.selectedItemList.value.some(s=>s.id==data.id)){
      return; 
    }
    this.coreSvc.selectedItemList.next([data]); 
    await this.init_ext_operations(data);
  }
  



}
